//
//  NetworkAccess.m
//  Pitch
//
//  Created by zhujinhui on 14-9-11.
//  Copyright (c) 2014年 zhujinhui. All rights reserved.
//

#import "NetworkAccess.h"
#import "BaseModel.h"
#import "Log.h"

#define TIME_OUT_INTERVEL 10

@implementation NetworkAccess


-(NetworkResponse *)doHttpRequest:(NSString *) requestUrl
           andParams:(NSDictionary *) params{
    if (![requestUrl hasPrefix:@"http://"]) {
        requestUrl = [NSString stringWithFormat:@"%@%@",HOST,requestUrl];
    }
    NSURL *rqstUrl = [NSURL URLWithString:requestUrl];
    //print a log
    NSLog(@"network url:%@",[rqstUrl absoluteString]);
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:rqstUrl];
    //time out
    request.timeoutInterval = TIME_OUT_INTERVEL;
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    NSError *parserError= nil;
    NSData *jsonData = nil;
    //judge if the value of the params is a object
    if (0x00 == params) {
        NSString *postString = @"{}";
        
        NSLog(@"post data:%@",postString);
        jsonData = [postString dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:jsonData];
    }else{
        NSMutableDictionary *tempDictionary = [[NSMutableDictionary alloc]initWithDictionary:params];
        NSInteger keyCount = [[tempDictionary allKeys] count];
        for (int i = 0; i < keyCount; ++i) {
            NSString *objectKey = [tempDictionary allKeys][i];
            id objectValue = [tempDictionary allValues][i];
            //if the value of the dictionary is a object ,then we should set it as a dictionary;
            if ([objectValue isKindOfClass:[BaseModel class]]) {
                BaseModel *baseModel = (BaseModel *) objectValue;
                NSDictionary *modelDictionary = [baseModel allProperties];
                [tempDictionary removeObjectForKey:objectKey];
                [tempDictionary addEntriesFromDictionary:modelDictionary ];
            }
        }
        @try {
            jsonData = [NSJSONSerialization dataWithJSONObject:tempDictionary options:NSJSONWritingPrettyPrinted error:&parserError];
            //print log,just used to show the post data
            NSString *postString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"post data:%@",postString);
            [request setHTTPBody:jsonData];
        }
        @catch (NSException *exception) {
            NSLog(@"#######");
            NSLog(@"%@:kyson exception :%@",self,exception);
            NSLog(@"#######");
            
        }
    }
    

    NSError *requestError = nil;
    //show the network activity indicator
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    //start request
    NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&requestError];
    //dismiss the network activity indicator
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    NetworkResponse * response = [[NetworkResponse alloc]init];
    if (requestError) {
        if (NSURLErrorCannotConnectToHost == requestError.code ) {
            response.errorMessage = @"连接服务器失败，请检查您的网络!";
            response.errorCode = NSURLErrorCannotConnectToHost;
        }else if (NSURLErrorTimedOut == requestError.code){
            response.errorMessage = @"超时，请检查您的网络!";
            response.errorCode = NSURLErrorTimedOut;
        }else if(NSURLErrorNotConnectedToInternet == requestError.code){
            response.errorCode = NSURLErrorNotConnectedToInternet;
            response.errorMessage = @"网络似乎已经断开";
        }else{
            response.errorCode = 89898989;
            response.errorMessage = @"校盟服务器被外星人劫持了!";
        }
    }else{
        NSString *resultString = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
        NSLog(@"kyson raw resultString:%@",resultString);
        response.rawJson = resultString;
    }
    
    
    return response;
    
}


@end
